package com.shebei.api.equipment_api_test.service;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class CheckPathParsing {

 @Autowired
private  JsonKeyParsing jsonKeyParsing;
    @Autowired
 private ParamParsing paramParsing;


    public String checkResponse(String checkPath,String response,Map<String,String> errorResult,String scene,String catogoryModule,String env){
          if(checkPath==null||checkPath.equals("")){
              return "false";
          }
           checkPath=paramParsing.parsingValue(checkPath,scene,catogoryModule,env);
        if(response ==null||response.equals("")){
            System.out.println("返回结果为：null 或者空" );
            return "false";
        }
        //判断响应是不是JSON 不是JSON 返回fasle
        Boolean isJosn=isJson(response);
        if(!isJosn){
            return "false";
        }
        JSONObject jsonToMap =  JSONObject.parseObject(checkPath);
        String  isTrue="true";  //默认期望结果和实际结果相等
        Iterator it =jsonToMap.entrySet().iterator();

        while (it.hasNext()) {
            Map.Entry<String, Object> entry = (Map.Entry<String, Object>) it.next();

            String keyPath=entry.getKey();
            String expectValue= String.valueOf( entry.getValue());
            String actualValue=jsonKeyParsing.getJsonKey( response, keyPath);

           String checkTrue=  checkExpect(expectValue,actualValue,keyPath,errorResult);

           if(checkTrue.equals("false")){  //只要一个条件判断为false,全局isTrue判断为false
               isTrue="false";
           }



        }

        return isTrue;

    }


    private String checkExpect(String expectValue,String actualValue,String keyPath,Map<String,String> errorResult){
            String isTrue="true";
            if(!expectValue.equals("notNull")){
                if(!expectValue.equals(actualValue)){   //期望结果和实际结果不等 记录结果 ，设置标签
                    errorResult.put(keyPath,"期望值："+expectValue+" 实际值："+actualValue);
                    isTrue="false";
                }
            }else {
                if(actualValue.equals("null")){
                    errorResult.put(keyPath,"期望值："+expectValue+" 实际值："+null);
                    isTrue="false";
                }
            }



        return isTrue;
    }


    public static boolean isJson(String content) {
        try {
            JSONObject.parseObject(content);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

}
